const express = require('express');
const md5 = require('blueimp-md5');

const router = express.Router();

const Channels = require('../models/Channels');
const News = require('../models/News');
const User = require('../models/User');

// 获取新闻频道数据
router.get('/channels', async (req, resp) => {
    console.log(req.headers);
    console.log('GET ALL Channels');
    let ret = await Channels.find();
    resp.json(ret);
});

// 获取新闻数据
router.get('/news', async (req, resp) => {
    console.log('GET ALL News');
    let ret =  await News.find();
    resp.json(ret);
});

// 账号登录
router.post('/signin', async (req, resp) => {
    console.log('User Login', req.body);
    let result = {};
    let ret =  await User.findOne({ useraccount: req.body.useraccount });
    if (ret) {
        // 用户已存在, 判断密码是否正确
        if (ret.password === md5(req.body.password) ) {
            result.statusCode = 0;
            result.message = '登录成功';
            result.data = ret;
        } else {
            result.statusCode = 2;
            result.message = '密码不正确';
        }
    } else {
        // 用户不存在
        result.statusCode = 2;
        result.message = '该用户不存在';
    }
    resp.json(result);
});

// 账号注册
router.post('/signup', async (req, resp) => {
    console.log('User Register', req.body);
    let result = {};
    let ret = await User.findOne({
        $or: [ 
            { username: req.body.username },
            { useraccount: req.body.useraccount }
        ] 
    });
    if (ret) {
        // 用户已存在
        result.statusCode = 2;
        result.message = '该用户已被注册';
    } else {
        // 用户不存在
        // 保存用户前对密码进行MD5加密
        req.body.password = md5(req.body.password);
        let loginUser = await new User(req.body).save();
        if (loginUser) {    // 如果 loginUser 为 null，表示注册失败
            result.statusCode = 0;
            result.message = '注册成功';
            result.data = loginUser;
        } else {
            result.statusCode = 2;
            result.message = '注册失败';
        }
    }
    resp.json(result);
});

module.exports = router;